package com.example.friendfindertwo;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

import com.example.friendfindertwo.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.plus.PlusClient;
import com.parse.Parse;
import com.parse.ParseAnalytics;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends Activity implements
ConnectionCallbacks, OnConnectionFailedListener{

	private static final int REQUEST_CODE_RESOLVE_ERR = 9000;

	private ProgressDialog mConnectionProgressDialog;
	public static PlusClient mPlusClient;
	private ConnectionResult mConnectionResult;
	public static ParseDatabase dataBaseObject = new ParseDatabase();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Parse.initialize(this, "TqoeslKt3kjTT52eifO6XVoWAUvwue9uBOCE0RDa", "FbAS9Uq5f52BoMbKiytqbbln9tttHUNY8ilaVpRx");

		// Set up Push Notifications
		ParseAnalytics.trackAppOpened(getIntent());

		mPlusClient =
				new PlusClient.Builder(this, this, this).setActions(
						"http://schemas.google.com/AddActivity", "http://schemas.google.com/BuyActivity")
						.setScopes("https://www.googleapis.com/auth/plus.login") // Space separated list of scopes
						.build();

		setContentView(R.layout.activity_login);

		mConnectionProgressDialog = new ProgressDialog(this);
		mConnectionProgressDialog.setMessage("Signing in...");

		if(!mPlusClient.isConnected()) mPlusClient.connect();

		if (mConnectionResult == null) {
			mConnectionProgressDialog.show();
		} else {
			try {
				Log.d("login","1");
				mConnectionResult.startResolutionForResult(LoginActivity.this, REQUEST_CODE_RESOLVE_ERR);

			} catch (SendIntentException e) {
				// Nouvelle tentative de connexion
				mConnectionResult = null;
				mPlusClient.connect();
			}
		}				
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */


	@Override
	public void onConnectionFailed(ConnectionResult result) {
		// TODO Auto-generated method stub
		if (mConnectionProgressDialog.isShowing()) {
			// L'utilisateur a d???????????????????????????j??????????????????????????? appuy??????????????????????????? sur le bouton de connexion. Commencer ??????????????????????????? r???????????????????????????soudre
			// les erreurs de connexion. Attendre jusqu'??????????????????????????? onConnected() pour masquer la
			// bo???????????????????????????te de dialogue de connexion.
			if (result.hasResolution()) {
				try {
					result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
				} catch (SendIntentException e) {
					mPlusClient.connect();
				}
			}
		}

		// Enregistrer l'intention afin que nous puissions lancer une activit??????????????????????????? lorsque
		// l'utilisateur clique sur le bouton de connexion.
		mConnectionResult = result;
	}

	@Override
	public void onConnected(Bundle connectionHint) {
		// TODO Auto-generated method stub
		mConnectionProgressDialog.dismiss();
		Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
		Log.d("login","is connected");
		Log.d("login",mPlusClient.getAccountName());

		String account = mPlusClient.getAccountName();	

		int index = account.indexOf("@");
		String temp = account.substring(index);
		account = account.replaceAll(temp, "");

		dataBaseObject.setAccountName(account);

		dataBaseObject.logUserConnection();

		Intent intent = new Intent(getApplicationContext(), SecondMap.class);

		//  intent.putExtra("account_name", mPlusClient.getAccountName());
		startActivity(intent);
	}




	@Override
	public void onDisconnected() {
		Toast.makeText(this, "disconnected!", Toast.LENGTH_LONG).show();	
		dataBaseObject.setOffline();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_CODE_RESOLVE_ERR && resultCode == RESULT_OK) {
			mConnectionResult = null;
			mPlusClient.connect();
		}
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub

		super.onRestart();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub

		super.onResume();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		mPlusClient.disconnect();
		/****get user row and put offline*/
		//dataBaseObject.userTable.put("online",false);
		super.onDestroy();
	}


}
